#include <OneWire.h>
OneWire  ds(TEMPPIN);        // ds18b20 pin #2 (middle pin) to Arduino pin 8

byte i;
byte present = 0;
byte data[12];
byte addr[8];
  
int HighByte, LowByte, SignBit, Whole, Fract, TReading, Tc_100, FWhole;

boolean temp_init() {
  Serial.print("inizializzazione temp: ");
  if (!ds.search(addr)) {
      Serial.println("No more addrs");
      delay(1000);
      ds.reset_search();
      return false;
  }
  Serial.print("INDIRIZZO COMPONENTE: ");
  for(int tmp=0; tmp<8; tmp++) Serial.print(addr[tmp], HEX);
  Serial.println("");
  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.print("CRC not valid!");
      delay(1000);
      return false;
  }
Serial.print("[OK]");
return true;
}

int temp_read() {
  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);
  present = ds.reset();
  ds.select(addr);    
  ds.write(0xBE);

  for ( i = 0; i < 9; i++) {
    data[i] = ds.read();
  }
  
  LowByte = data[0];
  HighByte = data[1];
  TReading = (HighByte << 8) + LowByte;
  SignBit = TReading & 0x8000;  // test most sig bit
  
  if (SignBit) {
    TReading = -TReading;
  }
  Tc_100 = (6 * TReading) + TReading / 4;    // multiply by (100 * 0.0625) or 6.25
  Whole = Tc_100 / 100;          // separate off the whole and fractional portions
  Fract = Tc_100 % 100;
  if (Fract > 49) {
    if (SignBit) {
      --Whole;
    } else {
      ++Whole;
    }
  } 
 return (SignBit)?-1*Whole:Whole;
 }

